package com.xzzz.backend.bsms.config;

import cn.hutool.core.util.StrUtil;
import com.xzzz.common.base.pojo.R;
import com.xzzz.common.base.util.ServletUtil;
import com.xzzz.common.base.util.spring.SpringUtil;
import com.xzzz.irda.auth.core.authorization.AuthContext;
import com.xzzz.irda.tracker.core.Tracker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.MethodParameter;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Slf4j
@RestControllerAdvice
public class ResponseBodyRAdvice implements ResponseBodyAdvice<Object>, EnvironmentAware {

    private boolean traceAdvice = false;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return traceAdvice;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof R) {
            R r = (R) body;
            try {
                if (AuthContext.getUserId() != null) {
                    String metadata = String.format("[id:%s]", AuthContext.getUserId());
                    r.setUserMetadata(metadata);
                }
                String api = ServletUtil.getUri();
                if (StrUtil.isNotBlank(api)) {
                    r.setApi(api);
                }
                r.setTraceId(Tracker.getTraceId());
            } catch (Exception ignored) {
            }
        }
        return body;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.traceAdvice = !"prod".equals(environment.getProperty(SpringUtil.PROFILE_ACTION));
    }
}
